// 日程管理工具函数

// 设置CSRF令牌
function setupCSRFToken() {
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
    return csrftoken;
}

// 配置FullCalendar
function configureCalendar(calendarEl, options = {}) {
    // 默认配置
    const defaultOptions = {
        initialView: 'dayGridMonth',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        selectable: true,
        eventClick: handleEventClick,
        select: handleDateSelect,
        eventDrop: handleEventDrop,
        eventResize: handleEventResize,
        events: []
    };

    // 合并自定义配置
    const mergedOptions = { ...defaultOptions, ...options };

    // 初始化日历
    const calendar = new FullCalendar.Calendar(calendarEl, mergedOptions);
    calendar.render();

    return calendar;
}

// 处理事件点击
function handleEventClick(info) {
    // 默认实现，可以在调用时被覆盖
    console.log('Event clicked:', info.event);
}

// 处理日期选择
function handleDateSelect(info) {
    // 默认实现，可以在调用时被覆盖
    console.log('Date selected:', info.startStr, info.endStr);
}

// 处理事件拖动
function handleEventDrop(info) {
    // 默认实现，可以在调用时被覆盖
    console.log('Event dropped:', info.event);
}

// 处理事件调整大小
function handleEventResize(info) {
    // 默认实现，可以在调用时被覆盖
    console.log('Event resized:', info.event);
}

// 发送AJAX请求
function sendAjaxRequest(url, method, data, successCallback, errorCallback) {
    const csrftoken = setupCSRFToken();

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken
        },
        body: data ? JSON.stringify(data) : null
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (successCallback) {
            successCallback(data);
        }
    })
    .catch(error => {
        console.error('AJAX Error:', error);
        if (errorCallback) {
            errorCallback(error);
        } else {
            showError('操作失败，请重试');
        }
    });
}

// 显示成功消息
function showSuccess(message) {
    const alert = document.createElement('div');
    alert.className = 'alert alert-success alert-dismissible fade show';
    alert.role = 'alert';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    document.body.appendChild(alert);

    setTimeout(() => {
        alert.remove();
    }, 3000);
}

// 显示错误消息
function showError(message) {
    const alert = document.createElement('div');
    alert.className = 'alert alert-danger alert-dismissible fade show';
    alert.role = 'alert';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    document.body.appendChild(alert);

    setTimeout(() => {
        alert.remove();
    }, 3000);
}

// 日期格式化
function formatDate(date, format = 'YYYY-MM-DD') {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');

    if (format === 'YYYY-MM-DD') {
        return `${year}-${month}-${day}`;
    } else if (format === 'MM/DD/YYYY') {
        return `${month}/${day}/${year}`;
    } else {
        return d.toLocaleDateString();
    }
}

// 导出工具函数
window.ScheduleUtils = {
    setupCSRFToken,
    configureCalendar,
    sendAjaxRequest,
    showSuccess,
    showError,
    formatDate
};